package com.juli.v2xdemo.tcp.protocol;

import android.text.TextUtils;
import android.util.Log;

import com.cz.basetool.CodeTool;
import com.cz.basetool.ui_work.util.log.AndroidConsoleLogPrinter;
import com.juli.v2xdemo.tcp.protocol.bean.CMD_55AA;


/**
 * Created by XinYi on 2019/4/15.
 * 55AA协议解析
 */
public class ProtocolDispatcher {
    private static final String TAG = "ProtocolDispatcher";
    private OnServerResponseResult onServerResponseResult;
    private static final ProtocolDispatcher ourInstance = new ProtocolDispatcher();
    private String remainData = "";     //残包

    /**
     * 消息数据的存放
     */
    private StringBuilder bufferReadMsg = new StringBuilder();


    public static ProtocolDispatcher getInstance() {
        return ourInstance;
    }

    private ProtocolDispatcher() {
        bufferReadMsg.setLength(0);
    }

    public void dispatch(String frame) {
        Log.d(TAG, "dispatch: " + frame);
        //在这里做分包判断
        if (!TextUtils.isEmpty(frame)) {
            step1_get_whole55AA(remainData + frame);
        }
    }

    private void step1_get_whole55AA(String aFrameData) {
        bufferReadMsg.append(aFrameData);
        String bufMsg = bufferReadMsg.toString();
        int head55AAIndex = bufMsg.indexOf(CMD_55AA.STX);
        if(head55AAIndex != -1){
            if(bufMsg.length() < 14){
                AndroidConsoleLogPrinter.d(TAG,"55AA数据不全，继续等待接收...");
                return;
            }
            int len = CodeTool.hex2Int(bufMsg.substring(4, 8));
            int wwaaFrameTotalLen = (4 + len)* 2;
            String WWAAStr = bufMsg.substring(0, wwaaFrameTotalLen);
            findOne55AA(WWAAStr);
            if(bufMsg.length() > wwaaFrameTotalLen){
                remainData = bufMsg.substring(wwaaFrameTotalLen);
            }else{
                remainData = "";
            }
        }else{
            remainData = "";
            AndroidConsoleLogPrinter.e(TAG,"step1_get_whole55AA 非55AA打头的数据");
        }
        bufferReadMsg.setLength(0);
    }

    private void findOne55AA(String whole55AAData){
        Log.e(TAG, "findOne55AA: << " + whole55AAData);
        if(onServerResponseResult != null){
             onServerResponseResult.onResponse(true,CMD_55AA.disassemble(whole55AAData));
        }
    }


    public void setOnServerResponseResult(OnServerResponseResult onServerResponseResult) {
        this.onServerResponseResult = onServerResponseResult;
    }

    public interface OnServerResponseResult {
        void onResponse(boolean success, CMD_55AA cmd_55AA);
    }
}
